package indi.zhifa.engine.core.excel.service;


import indi.zhifa.engine.core.common.entity.web.ServiceException;
import indi.zhifa.engine.core.excel.HzdlExcelSheetHandler;
import indi.zhifa.engine.core.excel.SheetConfig;
import indi.zhifa.engine.core.excel.entity.ExcelErrorInfo;
import indi.zhifa.engine.core.excel.entity.enums.EExcelErrorCode;
import indi.zhifa.engine.core.excel.entity.exception.ExcelException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.StringUtils;


public abstract class HzdlExcelService {

    protected SheetConfig[] mSheetConfigs;

    protected HzdlExcelService(SheetConfig[] pSheetConfig){
        mSheetConfigs = pSheetConfig;
    }

    protected void importExcel(Workbook pWorkbook) {
        for (SheetConfig config : mSheetConfigs) {
            Sheet sheet = pWorkbook.getSheet(config.getName());
            if (null == sheet) {
                ExcelErrorInfo errorInfo = new ExcelErrorInfo(EExcelErrorCode.SHEET_NOT_FOUND,
                        "沒有找到名为\"" + config.getName() + "\"的sheet");
                errorInfo.setSheetName(config.getName());
                throw new ServiceException(errorInfo.getErrorInfo());
            }
            HzdlExcelSheetHandler sheetHandler = config.getFactory().get();
            try {
                sheetHandler.readSheet(sheet, 0);
                String errMsg = sheetHandler.getErrMsg();
                if (StringUtils.hasText(errMsg)) {
                    throw new ServiceException(errMsg);
                }
                sheetHandler.save();
            } catch (ExcelException ex) {
                ex.printStackTrace();
                throw new ServiceException("在解析excel时发生错误，错误信息是" + ex);
            }
        }
    }

    protected void exportExcel(Workbook pWorkbook, Object pMask) {
        for (SheetConfig config : mSheetConfigs) {
            Sheet sheet = pWorkbook.getSheet(config.getName());
            if (null == sheet) {
                ExcelErrorInfo errorInfo = new ExcelErrorInfo(EExcelErrorCode.SHEET_NOT_FOUND,
                        "沒有找到名为\"" + config.getName() + "\"的sheet");
                errorInfo.setSheetName(config.getName());
                throw new ServiceException(errorInfo.getErrorInfo());
            }
            HzdlExcelSheetHandler sheetHandler = config.getFactory().get();
            try {
                sheetHandler.init();
                sheetHandler.analysisHeader(sheet);
                sheetHandler.loadData(pMask);
                sheetHandler.export(sheet);
            } catch (ExcelException | IllegalAccessException ex) {
                ex.printStackTrace();
                throw new ServiceException("在解析excel时发生错误，错误信息是" + ex);
            }
        }
    }
}
